from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response

from rango.forms import PageForm
from rango.models import Category, Page

from django.contrib.auth.decorators import login_required
from rango.view.category import get_category_list

from django.shortcuts import redirect

@login_required
def add_page(request, category_id):
    context = RequestContext(request)
    context_dict = {
        'categories': Category.objects.all(),
        'cat_list': get_category_list()}
    
    if request.method == "POST":
        form = PageForm(request.POST)
        
        if form.is_valid():
            page = form.save(commit=False)
            
            try:
                cat = Category.objects.get(id=category_id)
                page.category = cat
            except Category.DoesNotExist:
                return render_to_response('rango/add_page.html', context_dict, context)
            
            page.views = 0
            
            page.save()
                
            return category(request, category_id)
        else:
            print form.errors  
    else:
        form = PageForm()
        
    context_dict['category_id'] = category_id
    context_dict['form'] = form
    return render_to_response('rango/add_page.html', context_dict, context)
    
def track_url(request):
    context = RequestContext(request)
    page_id = None
    url = '/rango/'
    
    if request.method == 'GET':
        if 'page_id' in request.GET:
            page_id = request.GET['page_id']
            try:
                page = Page.objects.get(id=page_id)
                page.views = page.views + 1
                page.save()
                url = page.url
            except:
                pass

    return redirect(url)